package com.wangsai.framework.supersecurity.dubbo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wangsai.framework.supersecurity.core.SuperSecurityManager;
import com.wangsai.framework.supersecurity.core.UserRequest;
import com.wangsai.framework.supersecurity.core.context.chain.UserContextFilter;
import com.wangsai.framework.supersecurity.core.context.chain.UserContextFilterChain;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.rpc.RpcContext;

import java.util.Map;


/**
 * @author Mr.Wang
 * @date 2021-08-14 16:16
 */
@Slf4j
public class DubboUserContextFilter implements UserContextFilter {

    @Override
    public void doFilter(UserRequest userRequest, UserContextFilterChain filterChain) {
        String userMetadata = RpcContext.getContext().getAttachment(SuperSecurityManager.getConfig().getUserKey());
        if (!userRequest.isHasUser() && StringUtils.isNotBlank(userMetadata)) {
            try {
                JSONObject jsonObject = JSON.parseObject(SuperSecurityManager.getUserSecure().decode(userMetadata));
                for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
                    if (entry.getValue() == null) {
                        continue;
                    }
                    userRequest.getUser().put(entry.getKey(), entry.getValue());
                }
                userRequest.setHasUser(true);
            } catch (ClassCastException exception) {
                log.warn("用户类型转换出错");
            }
        }
        filterChain.doFilter(userRequest, filterChain);
    }
}